﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Text;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Web.SystemConfig.Services;
using DreamBuilder.Core.Container;

namespace Web
{
    public class CommonSearchHelper
    {

        private static List<ArchiveCondition> _archiveConditionList = null;

        public static List<ArchiveCondition> ArchiveConditionList
        {
            get
            {
                if (_archiveConditionList == null)
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin\\ArchiveFilterNewcfg.xml");

                    xmlDoc.Load(filePath);
                    string xmlString = xmlDoc.InnerXml;

                    XmlSerializer serializeObj = new XmlSerializer(typeof(List<ArchiveCondition>));
                    MemoryStream mstream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
                    _archiveConditionList = (List<ArchiveCondition>)serializeObj.Deserialize(mstream);
                }
                return _archiveConditionList;
            }
        }

        /// <summary>
        /// 点击过滤按钮时调用
        /// </summary>
        /// <param name="archiveType"></param>
        /// <param name="mySearchTable"></param>
        /// <returns></returns>
        public static string GetWhere(int archiveType, HtmlTable mySearchTable)
        {
            StringBuilder sb = new StringBuilder("  1=1  ");
            //构造Where
            ArchiveCondition archiveCondition = CommonSearchHelper.ArchiveConditionList.Find(m => m.ArchiveType == archiveType);
            if(archiveCondition == null)
                return string.Empty;
            DropDownList ddlOp;

            foreach (var item in archiveCondition.ConditionModelList)
            {
                if (item.Required == 0)
                    continue;

                switch (item.Type)
                {
                    case "textbox":
                    default:

                        ddlOp = mySearchTable.FindControl("ddlop" + item.FieldName) as DropDownList;
                        if (ddlOp != null)
                        {
                            TextBox txtBox = mySearchTable.FindControl("txt" + item.FieldName) as TextBox;

                            //条件非空
                            if (txtBox != null)
                            {
                                string txt = txtBox.Text.Trim().Trim('\'', '%', '&');
                                if (!string.IsNullOrEmpty(txt))
                                {
                                    if (ddlOp.SelectedValue.Equals("等于"))
                                    {
                                        sb.AppendFormat(" and {0} = '{1}'", item.FieldName, txt);
                                    }
                                    else
                                    {
                                        sb.AppendFormat(" and {0} like '%{1}%'", item.FieldName, txt);
                                    }
                                }
                                
                            }
                        }

                        break;
                    case "datebox":

                        TextBox txtStart = mySearchTable.FindControl("txtstart" + item.FieldName) as TextBox;
                        TextBox txtEnd = mySearchTable.FindControl("txtend" + item.FieldName) as TextBox;
                        if (txtStart != null || txtEnd != null)
                        {
                            string dateStart = txtStart.Text.Trim().Trim('\'', '%', '&');
                            string dateEnd = txtEnd.Text.Trim().Trim('\'', '%', '&');
                            DateTime dateValue;
                            if (DateTime.TryParse(dateStart, out dateValue))
                            {
                                sb.AppendFormat(" and {0} >= to_date('{1}','yyyy-mm-dd') ",item.FieldName,dateStart);
                            }
                            if (DateTime.TryParse(dateEnd, out dateValue))
                            {
                                sb.AppendFormat(" and {0} <= to_date('{1}','yyyy-mm-dd') ",item.FieldName, dateEnd);
                            }
                            
                        }

                        break;
                    case "select":

                        DropDownList ddlSelect = mySearchTable.FindControl("ddl" + item.FieldName) as DropDownList;
                        if (ddlSelect != null)
                        {
                            if (ddlSelect.SelectedIndex != -1 && !ddlSelect.SelectedValue.Equals("-1"))
                            {
                                sb.AppendFormat(" and {0} = '{1}' ", item.FieldName, ddlSelect.SelectedValue);
                            }
                        }

                        break;
                }
            }

            return sb.ToString();
        }

        /// <summary>
        /// 在 Page_Init 方法中调用
        /// 在ASP.NET中，页面初始化阶段是控件初始化
        /// 页面加载Page_Load阶段会将 ViewState 中的数据保存到控件上
        /// </summary>
        /// <param name="archiveType"></param>
        /// <param name="mySearchTable"></param>
        public static void BuildSearchTable(int archiveType, ref HtmlTable mySearchTable)
        {
            ArchiveCondition archiveCondition = CommonSearchHelper.ArchiveConditionList.Find(m => m.ArchiveType == archiveType);
            if (archiveCondition == null)
                return;
            foreach (var item in archiveCondition.ConditionModelList)
            {
                if (item.Required == 0)
                    continue;
                HtmlTableRow row = new HtmlTableRow();

                //标题
                HtmlTableCell th = new HtmlTableCell();
                th.InnerText = item.Title;
                th.Width = "80";
                row.Cells.Add(th);

                DropDownList ddl;
                HtmlTableCell opCell;
                HtmlTableCell contentCell;

                switch (item.Type)
                {
                    case "textbox":
                    default:

                        //操作符
                        ddl = new DropDownList();
                        ddl.EnableViewState = true;
                        ddl.ID = "ddlop" + item.FieldName;
                        ddl.Attributes["name"] = "ddlop" + item.FieldName;
                        ddl.Attributes["class"] = "easyui-combobox";
                        ddl.Items.Add(new ListItem { Text = "包含", Selected = true });
                        ddl.Items.Add(new ListItem { Text = "等于" });

                        opCell = new HtmlTableCell();
                        opCell.Width = "130";
                        opCell.Controls.Add(ddl);
                        row.Cells.Add(opCell);

                        //输入框
                        contentCell = new HtmlTableCell();
                        TextBox txtBox = new TextBox();
                        txtBox.EnableViewState = true;
                        txtBox.ID = "txt" + item.FieldName;
                        txtBox.Attributes["name"] = "txt" + item.FieldName;

                        contentCell.Controls.Add(txtBox);

                        row.Cells.Add(contentCell);

                        break;
                    case "datebox":

                        //输入框
                        contentCell = new HtmlTableCell();
                        TextBox txtStartdateBox = new TextBox();
                        txtStartdateBox.EnableViewState = true;
                        //txtStartdateBox.Text = DateTime.Now.AddYears(-1).ToString("yyyy-MM-dd");
                        txtStartdateBox.ID = "txtstart" + item.FieldName;
                        txtStartdateBox.Attributes["name"] = "txtstart" + item.FieldName;
                        txtStartdateBox.Attributes["class"] = "easyui-datebox";
                        contentCell.Controls.Add(txtStartdateBox);
                        row.Cells.Add(contentCell);

                        HtmlTableCell contentCell1 = new HtmlTableCell();
                        TextBox txtEnddateBox = new TextBox();
                        txtEnddateBox.EnableViewState = true;
                        //txtEnddateBox.Text = DateTime.Now.ToString("yyyy-MM-dd");
                        txtEnddateBox.ID = "txtend" + item.FieldName;
                        txtEnddateBox.Attributes["name"] = "txtend" + item.FieldName;
                        txtEnddateBox.Attributes["class"] = "easyui-datebox";
                        contentCell1.Controls.Add(txtEnddateBox);

                        row.Cells.Add(contentCell1);

                        break;
                    case "select":

                        //操作符
                        ddl = new DropDownList();
                        ddl.EnableViewState = true;
                        ddl.ID = "ddlop" + item.FieldName;
                        ddl.Attributes["name"] = "ddlop" + item.FieldName;
                        ddl.Attributes["class"] = "easyui-combobox";
                        ddl.Items.Add(new ListItem { Text = "等于", Selected = true });

                        opCell = new HtmlTableCell();
                        opCell.Width = "130";
                        opCell.Controls.Add(ddl);
                        row.Cells.Add(opCell);

                        //下拉框
                        contentCell = new HtmlTableCell();
                        DropDownList ddlValues = new DropDownList();
                        ddlValues.EnableViewState = true;
                        ddlValues.ID = "ddl" + item.FieldName;
                        ddlValues.Attributes["name"] = "ddl" + item.FieldName;
                        ddlValues.Attributes["class"] = "easyui-combobox";

                        ICodeTable codeTable = UContainer.Resolve<ICodeTable>();

                        string codeType = item.FieldName.ToUpper();
                        if(codeType.StartsWith("F_"))
                            codeType = codeType.Substring(2);

                        ddlValues.DataSource = codeTable.GetCodeTableDataByType(codeType).Tables[0];
                        ddlValues.DataTextField = "CODE_DESC";
                        ddlValues.DataValueField = "CODETABLEID";
                        ddlValues.DataBind();
                        ddlValues.Items.Insert(0, new ListItem("-请选择-", "-1"));

                        contentCell.Controls.Add(ddlValues);

                        row.Cells.Add(contentCell);

                        break;
                }
                mySearchTable.Rows.Add(row);
            }

        }
    }
}